package cc.fs.zhihuapp.ui.activity.demo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cc.fs.zhihuapp.AppConfig;
import cc.fs.zhihuapp.R;
import cc.fs.zhihuapp.ui.activity.helper.BaseActivity;
import cc.fs.zhihuapp.ui.adapter.SmbDataAdapter;
import cc.fs.zhihuapp.utils.Cache;
import cc.fs.zhihuapp.utils.SmbUtils.SmbProxy;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;

/**
 * Created by fostion on 2015/11/21.
 */
public class WanFileActivity extends BaseActivity {


    private final int HANDLER_GET_FILE = 101;

    @InjectView(R.id.toolbar)
    Toolbar toolbar;
    @InjectView(R.id.recycler_view)
    RecyclerView recyclerView;
    ArrayList<SmbFile> smbfiles;
    SmbDataAdapter adapter;
    LinearLayoutManager linearLayoutManager;
    String host = "192.168.1.101";
    String account = "admin";
    String password = "123456";

    SmbProxy proxy;
    String rootPath;
    String currentPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data);
        ButterKnife.inject(this);

        AppConfig.init(this);

        host = AppConfig.get("host");
        account = AppConfig.get("account");
        password = AppConfig.get("password");

        toolbar.setTitle("局域网文件映射器");
        setSupportActionBar(toolbar);
        proxy = new SmbProxy();
        proxy.startProxy();
        setUpView();

        getFormatUrl("");
    }

    private void setUpView() {
        smbfiles = new ArrayList<>();
        adapter = new SmbDataAdapter(smbfiles);
        recyclerView.setAdapter(adapter);
        linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);

        adapter.setOnItemClickListener(new SmbDataAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(SmbFile smbFile) {
                try {
                    if (smbFile.isDirectory()) {
                        getFiles(smbFile.toString());
                    } else {
                        String path = smbFile.toString();
                        String url = path.substring(path.indexOf("admin"));
                        url = proxy.getFormatUrl(url);
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        Uri data = Uri.parse(url);
                        intent.setDataAndType(data, "video/*");
                        startActivity(intent);
                    }
                } catch (SmbException e) {
                    e.printStackTrace();
                }
            }
        });


    }

    private void getFiles(final String path) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    smbfiles.clear();
                    SmbFile smbfile = new SmbFile(path);
                    smbfiles.addAll(Arrays.asList(smbfile.listFiles()));
                    currentPath = path;
                    Message msg = new Message();
                    msg.what = HANDLER_GET_FILE;
                    sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e(" ------ ", " 无法获取局域网中文件 ");
                }
            }
        }).start();
    }

    public String getFormatUrl(String url) {
        currentPath = String.format("smb://%s:%s@%s/", account, password, host + url);
        rootPath = currentPath;
        return currentPath;
    }

    @Override
    public void onBackPressed() {
        if (!currentPath.equals(rootPath)) {
            try {
                SmbFile smbFile = new SmbFile(currentPath);
                currentPath = smbFile.getParent();
                getFiles(currentPath);
                return;
            } catch (Exception e) {
            }
        }
        super.onBackPressed();
    }

    @Override
    public void handler(Message msg) {
        switch (msg.what) {
            case HANDLER_GET_FILE:
                adapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_wan_file, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.setting) {

            View contentView = getLayoutInflater().inflate(R.layout.dialog_setting, null);
            final EditText hostName = (EditText)contentView.findViewById(R.id.host);
            final EditText accountName = (EditText)contentView.findViewById(R.id.account);
            final EditText passwordName = (EditText)contentView.findViewById(R.id.password);
            hostName.setText(host);
            accountName.setText(account);
            passwordName.setText(password);
            new AlertDialog.Builder(this)
                    .setView(contentView)
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    })
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            host = hostName.getText().toString();
                            account = accountName.getText().toString();
                            password = passwordName.getText().toString();
                            getFiles(getFormatUrl(""));
                        }
                    }).show();

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        if(proxy != null){
            proxy.stopProxy();
        }
        AppConfig.save("host",host);
        AppConfig.save("account",account);
        AppConfig.save("password",password);
        super.onDestroy();
    }
}
